package com.my12306.third.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.baomidou.mybatisplus.extension.api.Assert;
import com.my12306.common.util.DateUtils;
import com.my12306.third.model.vo.OssPolicyResult;
import com.my12306.third.service.OssService;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;


/**
 * @Author:苏牧夕
 * @Date:2020/5/13 23:57
 * @Version 1.0
 * oss 对象存储 服务类
 */
@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OSSClient ossClient;
    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrifix;
    @Value("${aliyun.oss.policy.expire}")
    private long expire;
    @Value("${aliyun.oss.endpoid}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucket;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;// AccessKeyId。
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Override
    public OssPolicyResult policy() {
        String filePrefix = dirPrifix + DateUtils.getDate();
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
//        String callbackUrl = "http://88.88.88.88:8888";
        OssPolicyResult result = new OssPolicyResult();
        try {
            long expireEndTime = System.currentTimeMillis() + expire * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, filePrefix);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            result.setAccessKeyId(accessKeyId);
            result.setPolicy(encodedPolicy);
            result.setSignature(postSignature);
            result.setDir(filePrefix);
            result.setHost(host);
            result.setExpire(expireEndTime / 1000);
            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            result.setCallback(base64CallbackBody);
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        return result;
    }

    @Override
    public String ossFileUpload(MultipartFile file) throws IOException {
// Endpoint以杭州为例，其它Region请按实际情况填写。
// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。

// 创建OSSClient实例。
// 上传文件流。
        if (file == null) return null;
//        InputStream inputStream = new FileInputStream();
//        ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);

// 关闭OSSClient。
        ossClient.shutdown();
        return null;
    }
}
